package com.alan.socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * 简单服务端
 * Created by Alan on 2017/8/5.
 */
public class Server {

    public static void main(String[] args) {
        //创建一个服务器对象
        ServerSocket ss = null;
        Socket socket = null;
        try {
            ss = new ServerSocket(8888);

            //服务器进入就绪状态
            socket = ss.accept();
            System.out.println("-------");
            //通过Socket得到输入输出流
            InputStream is = socket.getInputStream();
            OutputStream os = socket.getOutputStream();

            //将字节流转化为字符流
            PrintWriter pw = new PrintWriter(os,true);
            BufferedReader br = new BufferedReader(new InputStreamReader(is));

            Scanner input = new Scanner(System.in);

            while (true){
                //打印接受的消息
                String info = br.readLine();
                System.out.println(info);

                String send = input.nextLine();
                pw.println("服务器端说："+send);

            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(ss != null){
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
